<template>
  <div>
    <div style="height: 100%;">
      <!-- 背景图片，之后替换为GIS -->
      <div class="header-content"> <img class="header-icon" referrerpolicy="no-referrer"
          src="@/assets/img/module1/page1top2.png" />
        <span class="header-title">空域运行管理</span>
      </div>
      <!-- <div class="header-content">
        <img class="header-icon" referrerpolicy="no-referrer" src="@/assets/img/module1/page1top2.png" />
        <span class="header-title">空域运行管理</span>
      </div> -->
      <div id="cesiumContainer" style="height: 54.5rem; margin-top: 0.5%;"></div>
      <!-- <img class="image_3" referrerpolicy="no-referrer" src="@/assets/img/module2/temp/tempgis.png" /> -->

      <div class="left-panel-container">
        <div class="img_left_title">
          <img src="@/assets/img/module2/content.png" style="width: 100%" />
          <img src="@/assets/img/module2/snailtitleicon.png" style="position: absolute; top: 3px; left: 15px" />
          <span class="text_left_title">空域对象列表</span>
        </div>
        <button v-if="!tableVisible" class="table-button-display" @click="tableVisible = true">显示</button>
        <button v-if="tableVisible" class="table-button-hidden" @click="tableVisible = false">隐藏</button>


        <!-- 功能输入按钮部分 -->
        <div v-if="tableVisible" class="table-actions">
          <select v-model="searchQuery" @change="filterTable" class="search-input">
            <option value="">请选择区域类型</option>
            <option value="航路">航路</option>
            <option value="起降区">起降区</option>
            <option value="作业区">作业区</option>
            <option value="特殊区域">特殊区域</option>
          </select>
          <!-- 刷新按钮 -->
          <!-- <el-button @click="refreshTable" icon="el-icon-refresh" type="primary">刷新</el-button> -->

        </div>
        <div v-if="tableVisible" class="table-context">
          <CustomTable :data="tableData" :columns="columns" @viewDetails="handleViewDetails"
          @hoverLeave="hoverLeave" height="100%" ref="customTable" />


          <!-- <div class="table-container2">
        <SimpleTable :title="'某某某文件列表'" :tableData.sync="fileData" :rowHeight="30" @row-selected="handleRowSelected" />
        <div style="color: azure;">
          <h4>选中的数据：</h4>
          <pre>{{ selectedRow }}</pre> 
        </div>
      </div> -->


        </div>
      </div>
      <!-- <CustomTable :data="tableData" :columns="columns" :pageSize="8" @viewDetails="handleViewDetails" /> -->

      <!-- <h3>模块一、模块四、模块五可复用列表组件</h3> -->
      <!-- <div class="table-container2">
        <SimpleTable :title="'某某某文件列表'" :tableData.sync="fileData" :rowHeight="30" @row-selected="handleRowSelected" />
        <div style="color: azure;">
          <h4>选中的数据：</h4>
          <pre>{{ selectedRow }}</pre> 
        </div>
      </div> -->

      <!-- 弹窗内容 -->
      <div class="right-panel-container" v-if="statusDialogVisible">
        <CustomDialog :statusDialogVisible="statusDialogVisible"
          :selectedObjectName="selectedDetails.airspaceObjectName" :selectedObjectId="selectedDetails.id"
           @update:statusDialogVisible="statusDialogVisible = $event">
        </CustomDialog>
      </div>

      <!-- 确认提交弹窗 -->

      <!-- <el-dialog
  title="提示"
  :visible.sync="cofirmSubmitDialogVisible"
  width="20%"
  top="30vh"
  center>
  <span>请确认是否提交</span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cofirmUploadTrue">确 认</el-button>
    <el-button type="primary" @click="cofirmUploadFalse">取 消</el-button>
  </span>
</el-dialog> -->
      <!--<CustomDialogConfirm
        :visible.sync="cofirmSubmitDialogVisible"
        width="600px"
        height="300px"
      >
      </CustomDialogConfirm>-->
    </div>
  </div>
</template>

<script>
import CustomTable from "@/components/CustomTableModule6.vue";
// import CustomDialogConfirm from "@/components/CustomDialogModule2Confirm.vue";
import CustomDialog from "@/components/CustomDialogModule6Information.vue";
// import Xmap from "";
import { drawCircleArea, drawParallelogramArea, drawSquareArea } from '@/utils/draw2DShapes.js';
import { drawCylinderArea } from '@/utils/draw3DShapes.js';
import { draw3DPipelineTrack, draw3DRectangularPipelineTrack } from '@/utils/drawPipeline.js';
import { drawLine } from '@/utils/drawPath.js';
import { draw3DRectangularPipelineTrackM1_2, draw3DPolygonalPrismM1, drawCylinderAreaM1 } from '@/utils/draw3D-module6.js';

import axios from "axios";
// import "@/mock/mockmodule2ps.js"; // 引入 mock.js
export default {
  name: "Module6AirspaceManage",
  components: {
    CustomTable,
    // CustomDialogConfirm,
    CustomDialog,
  },
  data() {
    return {
      statusDialogVisible: false, // 状态弹窗显示
      cofirmSubmitDialogVisible: false,
      selectedDetails: {
        startTime: "20240510T08:00:00",
        endTime: "20240510T10:00:00",
      }, // 存储选中的行数据
      selectedSort: "id", // 默认按序号排序
      searchQuery: "", // 搜索关键字
      inverseSort: true, // 排序顺序，默认升序
      fileList: [], // 上传文件列表
      tableData: [], // 表格数据从服务器获取
      columns: [
        { prop: "index", label: "#" },
        { prop: "airspaceObjectName", label: "空域对象名称" },
        { prop: "airLaneType", label: "空域类型" },
      ],
      tableVisible: true,
    };
  },
  async mounted() {
    // 页面加载时获取数据
    const future = this.fetchTableData();
    this.initializeCesium();
    // const xmap = new Xmap.Viewer('cesiumContainer');
    // Xmap.Operates.Fly.camaraFlyToPosition({
    //   lng: 120, lat: 20, height: 10000
    // },null,0);
    // Xmap.AirspaceManage.HierarchicalGrid.ShowGridsWithLevelDynamic();
    await future;
    this.updateRoutes();
    this.updatePolygonAreas();
    this.updateCircleAreas();
  },
  beforeDestroy() {
    // 在这里执行组件销毁的逻辑
    // 比如清除定时器，或手动调用一些清理方法
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  },

  methods: {
    // watch: {
    //   activeTab(newVal) {
    //     this.updateDetails(); // 切换模块时更新详细信息
    //   }
    // },

    // 获取表格数据
    async fetchTableData() {
      try {
        // const response = await axios.post("http://127.0.0.1:4523/m2/5156778-4821166-default/215427762", {
        //   sort: this.selectedSort,
        //   query: this.searchQuery,
        //   inverse: this.inverseSort,
        // });
        const response = await axios.post(
          "http://47.99.75.194:8086/module6/searchall",
          null,
          {
            params: {
              keyword: this.searchQuery,
            },
          }
        );

        console.log(response);
        if (response.data.code === 0) {
          console.log("Hello");
          // 处理返回的data，从中取出correspondingTimePeriod分为startTime和endTime
          this.tableData = [];
          // 初始化计数器
          let index = 1;
          response.data.data.forEach((item) => {
            // const regex = /\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*/;
            // const matches = item.correspondingTimePeriod.match(regex);
            const newItem = {
              ...item,
              index,
            };
            if (item.airspaceObjectName.includes("起降")) {
              newItem.airLaneType = "起降区";
            }
            if (item.airspaceObjectName.includes("作业")) {
              newItem.airLaneType = "作业区";
            }
            if (item.airspaceObjectName.includes("航路")) {
              newItem.airLaneType = "航路";
            }
            this.tableData.push(newItem);
            index++;
          });

          // this.tableData = response.data.data;
        }
      } catch (error) {
        console.error("获取表格数据失败", error);
      }
    },
    sortTable() {
      // 重新获取排序后的数据
      this.fetchTableData();
    },
    sortInverse() {
      this.inverseSort = !this.inverseSort;
      // console.log(this.inverseSort);
      this.fetchTableData();
    },

    filterTable() {
      // 触发搜索过滤，重新获取数据
      this.fetchTableData();
    },
    refreshTable() {
      // 刷新表格数据，重置搜索和排序
      this.selectedSort = "id";
      this.searchQuery = "";
      this.fetchTableData();
    },
    handleViewDetails(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
      // console.log("selectedDetails", this.selectedDetails);
    },
    hoverLeave() {
      this.statusDialogVisible = false;
    },

    submitVisibleChange() {
      this.cofirmSubmitDialogVisible = true;
    },
    // 绘制航路折线
    updateRoutes() {
      // 清除之前的实体
      // this.viewer.entities.removeAll();
      // console.log("tableData1111", this.tableData);
      // 遍历表格数据，找到航路数据
      this.tableData.forEach((item) => {
        console.log("item", item)
        this.tableData.forEach((item) => {
          if (item.airLaneType === "航路" && item.shapeObj) {
            const positions = [];
            const pointNames = [];
            const sizes = [];

            // 提取经纬度和高度，并生成每段的宽高
            item.shapeObj.forEach((point, index) => {
              positions.push(point.longitude, point.latitude, point.altitude);
              pointNames.push(`${item.airspaceObjectName} - 点${index + 1}`);

              if (index < item.shapeObj.length - 1) {
                sizes.push([500, 200]); // 宽度为500米，高度为200米
              }
            });
            // console.log("positions", positions);
            // console.log("sizes", sizes);
            // 调用自定义的绘制方法
            draw3DRectangularPipelineTrackM1_2(this.viewer, positions, sizes, 'YELLOW', pointNames);
          }
        });
      });

      // 缩放视图到新添加的航路
      this.viewer.zoomTo(this.viewer.entities);
    },
    updatePolygonAreas() {
      // 清除之前的实体
      // this.viewer.entities.removeAll();

      // 遍历表格数据，找到多边形区域数据
      this.tableData.forEach((item) => {
        if (item.polygonShapeObj && item.polygonShapeObj.length > 0) {
          const positions = [];
          const pointNames = [];
          let minHeight = Number.POSITIVE_INFINITY;
          let maxHeight = Number.NEGATIVE_INFINITY;

          // 提取经纬度和高度
          item.polygonShapeObj.forEach((point, index) => {
            positions.push(point.longitude, point.latitude);
            pointNames.push(`${item.airspaceObjectName} - 点${index + 1}`);

            // 计算最小和最大高度
            if (point.minAltitude < minHeight) {
              minHeight = point.minAltitude;
            }
            if (point.maxAltitude > maxHeight) {
              maxHeight = point.maxAltitude;
            }
          });

          // 使用自定义方法绘制多边形柱状体
          draw3DPolygonalPrismM1(
            this.viewer,
            positions,
            minHeight,
            maxHeight,
            'BLUE',
            0.5,
            pointNames
          );
        }
      });

      // 缩放视图到新添加的区域
      this.viewer.zoomTo(this.viewer.entities);
    },
    // 绘制圆形区域
    updateCircleAreas() {
      // this.viewer.entities.removeAll();

      this.tableData.forEach((item) => {
        if (item.circleShapeObj && item.circleShapeObj.length > 0) {
          item.circleShapeObj.forEach((circlePoint) => {
            console.log("circlePoint", circlePoint);
            const lon = circlePoint.longitude;
            const lat = circlePoint.latitude;
            const minHeight = circlePoint.minAltitude;
            const maxHeight = circlePoint.maxAltitude;
            const radius = circlePoint.radius;

            // 调用绘制方法
            drawCylinderAreaM1(this.viewer, lon, lat, minHeight, maxHeight, radius, 'BLUE', 0.5);
          });
        }
      });

      this.viewer.zoomTo(this.viewer.entities);
    },
    async initializeCesium() {
      try {
        this.viewer = new Cesium.Viewer('cesiumContainer', {
          sceneModePicker: false,
          baseLayerPicker: false,
          geocoder: false,
          homeButton: false,
          navigationHelpButton: false,
          infoBox: false,
          timeline: false,
          animation: false
        });
        this.viewer.scene.frameState.creditDisplay.container.style.display = 'none';

        // 设置初始相机视图
        this.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(113.5, 22.1, 10000)
        });

      } catch (error) {
        console.error('Cesium initialization failed:', error);
      }
    },
  },

  watch: {
    // 监听 statusDialogVisible 的变化
    statusDialogVisible(newValue, oldValue) {
      if (newValue === false && oldValue === true) {
        // 当 statusDialogVisible 从 1 变为 0 时，调用子组件的 resetSelection 方法
        this.$refs.customTable.resetSelection();
        console.log("resetSelection called");
      }
    },
  },
};
</script>


<style scoped lang="css">
h3 {
  color: #ffffff;
}

/* 顶部内容区样式 */
.header-content {
  position: relative;
  width: 100%;
  /* 使其占据整个宽度 */
  height: 10%;
  background: url("@/assets/img/module1/page1top.png") no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  padding: 5px;
  /* 增加内部间距 */
}

/* 标题样式 */
.header-title {
  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  position: relative;
  flex: 2;
  margin-left: 5%;
  width: 20%;
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  text-align: left;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 图标样式 */
.header-icon {
  position: relative;
  width: 22px;
  height: 20px;
  margin-left: 20px;
  /* 与其他内容间隔 */
  margin-top: -20px;
}

.image_3 {
  position: absolute;
  /* 图片绝对定位，不影响布局 */
  top: 14%;
  left: 15%;
  width: 80%;
  /* 让图片宽度覆盖整个容器 */
  height: 80%;
  /* 让图片高度覆盖整个容器 */
  z-index: 0;
  /* 将背景图片置于内容下层 */
}

.left-panel-container {
  position: absolute;
  /* 固定在左上角 */
  top: 170px;
  left: 300px;
  width: 300px;
  /* min-width: 300px; */
  /* 面板的宽度 */
  height: auto;
  /* 面板的高度，占据整个视口高度 */
  /* background-color: #333; */
  /* 面板的背景颜色 */
  color: white;
  /* 面板中的文字颜色 */
  padding: 20px;
  /* 内边距 */
  z-index: 1;
  /* 确保面板显示在其他元素上方 */
}

.right-panel-container {
  position: absolute;
  /* 固定在左上角 */
  top: 15%;
  right: 5%;
  width: 30%;
  /* 面板的宽度 */
  height: 76%;
  /* 面板的高度，占据整个视口高度 */
  /* background-color: #333; */
  /* 面板的背景颜色 */
  color: white;
  /* 面板中的文字颜色 */
  padding: 20px;
  /* 内边距 */
  z-index: 1;
  /* 确保面板显示在其他元素上方 */
}

.img_left_title {
  position: relative;
  left: 0%;
  top: 5%;
  background-size: 100% 100%;
  /* background-color: rgba(200, 215, 228, 1); */
}

.text_left_title {
  position: absolute;
  left: 19%;
  top: 5.9%;
  width: 60%;

  overflow-wrap: break-word;

  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 23px;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.table-actions {
  position: relative;
  /* background-color: #ffffff; */
  /* left: 5%;
  top: 10%; */
  z-index: 1;
  width: 300px;
  height: 30px;
}

.search-input {
  position: relative;
  left: 0%;
  top: 6%;
  height: 100%;
  width: auto;
  z-index: 1;
  border: none;
  background-image: url("@/assets/img/module2/search.png");
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-color: transparent;
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  /* color: #ffffff; */
  padding-left: 10px;
  /* 添加内边距 */
  font-family: AlibabaPuHuiTi_2_55_Regular;
  font-weight: NaN;
  color: white;
}

.search-input option {
  /* background-color: #000000; 背景颜色 */
  color: black;
  /* 文字颜色 */
  font-family: AlibabaPuHuiTi_2_55_Regular;
  font-weight: normal;
  padding: 5px;
  /* 内边距 */
}

.search-input::placeholder {
  font-family: AlibabaPuHuiTi_2_55_Regular;
  color: #ffffff;
  font-weight: NaN;
  font-size: 14px;
  padding-left: 6px;
  /* 添加内边距 */
}

.filter-button {
  background-image: url("@/assets/img/module2/filtericon1.png");
  position: absolute;
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  left: 18%;
  top: 24%;
  width: 15px;
  height: 15px;
  z-index: 3;
  border: none;
  cursor: pointer;
  filter: brightness(0.1);
}

.filer-button:active {
  opacity: 0.8;
  /* 点击时使按钮变暗 */
}

.sort-select {
  position: absolute;
  left: 22%;
  top: 6%;
  width: 18%;
  height: 60%;
  z-index: 1;
  background-image: url("@/assets/img/module2/search.png");
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  border: none;
  /* 去除边框 */
  border-radius: 4px;
  /* 设置圆角 */
  color: #ffffff;
  /* 设置文字颜色 */
  padding-left: 10px;
  /* 设置左侧内边距 */
  font-size: 14px;
  font-family: AlibabaPuHuiTi_2_55_Regular;
  font-weight: NaN;
}

.sort-button {
  background-image: url("@/assets/img/module2/sorticon1.png");
  position: absolute;
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  left: 40%;
  top: 11%;
  width: 5%;
  height: 60%;
  z-index: 3;
  border: none;
  cursor: pointer;
}

.table-container2 {
  position: absolute;
  left: 50%;
  top: 6%;
  width: 30%;
  height: 80%;
  z-index: 1;
  display: block;
}

.table-context {
  position: relative;
  /* background-color: rgb(0, 247, 255); */
  /* left: 5%;
  top: 15%; */
  z-index: 1;
  width: 300px;
  height: auto;
}

/* 旧元素 */

.plan-diolog {
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  height: 80%;
  /* 设置高度，使布局固定 */
}

.plan-diolog-left-pane {
  width: 45%;
  /* 左侧占 50% 宽度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.plan-diolog-left-up-pane {
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.plan-diolog-left-down-pane {
  padding: 10px;
  border-radius: 5px;
}

.plan-diolog-right-pane {
  width: 55%;
  /* 右侧占 35% 宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
}

h1 {
  color: #ffffff;
}

h2 {
  color: #ffffff;
}

h3 {
  color: #ffffff;
}

.table-button-display {
  background-image: url('@/assets/img/module1/button-tijiao.png');
  position: absolute;
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  background-color: transparent;
  color: transparent;
  right: 0%;
  /* left: 46%; */
  /* top: 5%; */
  height: 30px;
  width: 50px;
  border: none;
  cursor: pointer;
  color: white;
  font-size: 16px;
  text-align: center;
  line-height: 8px;
  z-index: 2;
}

.table-button-hidden {
  background-image: url('@/assets/img/module1/button-bohui.png');
  position: absolute;
  background-size: 100% 100%;
  /* 背景图片覆盖按钮大小 */
  background-color: transparent;
  color: transparent;
  right: 0%;
  /* left: 46%; */
  /* top: 5%; */
  height: 30px;
  width: 50px;
  border: none;
  cursor: pointer;
  color: white;
  font-size: 16px;
  text-align: center;
  line-height: 8px;
  z-index: 2;
}
</style>
